<template>
	<view>
		<cu-custom bgColor="bg-black" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">聊天</block>
		</cu-custom>
		<scroll-view @scrolltoupper='scrolltoupper' id="scrollview" class="chat-window" :scroll-y="scrollY" :style="{height: style.contentViewHeight + 'px'}"
		 :scroll-with-animation="false" :scroll-top="scrollTop">
			<view class="cu-chat">
				<!-- <view v-if="isSHow == true" class="cu-load bg-blue loading">
					加载中
				</view> -->
				<view v-for="item in dataList" :key='item.id' :class="item.fromUserId==userMsg.id?'cu-item self':'cu-item'">
					<view v-if="item.fromUserId!=userMsg.id" class="cu-avatar radius" :style="{backgroundImage:'url('+ item.fromUserIdHandlUrl +')'}"></view>
					<view class="main">
						<view class="content shadow">
							{{item.content}}
						</view>
					</view>
					<view v-if="item.fromUserId==userMsg.id" class="cu-avatar radius" :style="{backgroundImage:'url('+ item.fromUserIdHandlUrl +')'}"></view>
					<view class="date">{{item.createTime}}</view>
				</view>
			</view>

		</scroll-view>


		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<view class="action">
				<text class="cuIcon-sound text-grey"></text>
			</view>
			<input v-model="content" class="solid-bottom" :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10"
			 @focus="InputFocus" @blur="InputBlur"></input>
			<view class="action">
				<text class="cuIcon-emojifill text-grey"></text>
			</view>
			<button @click="handSub" class="cu-btn bg-green shadow">发送</button>
		</view>

	</view>
</template>

<script>
	import config from "../../config/config.js"
	export default {
		data() {
			return {
				InputBottom: 0,
				socketTask: null,
				is_open_socket: false,
				userMsg: {},
				roomId: "",
				newitem: {},
				content: '',
				dataList: [],
				scrollTop: 0,
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 90,
					mitemHeight: 0
				},
				page: 1,
				per_page: 10,
				scrollY: true,
				imgUrl: '',
				isSHow: false
			};
		},
		async onLoad(e) {

			if (e.item) {
				this.newitem = JSON.parse(e.item)
				console.log(e.imgUrl, 'e.imgUrl')
				this.imgUrl = e.imgUrl
			}
			if (uni.getStorageSync('USER')) {
				this.userMsg = JSON.parse(uni.getStorageSync('USER'))
			}
			await this.connectSocketInit()
			this.getMore()
			const res = uni.getSystemInfoSync(); //获取手机可使用窗口高度     api为获取系统信息同步接口
			this.style.pageHeight = res.windowHeight;
			this.style.contentViewHeight = res.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (100) - 70;
			setTimeout(() => {
				this.scrollToBottom()
			}, 100)

		},
		methods: {
			scrolltoupper() {

				this.loadMore()

				// console.log('到顶部了', this.scrollTop)
			},
			handSub() {
				console.log(this.is_open_socket)
				let that = this
				if (this.is_open_socket) {
					// websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
					// this.userMsg.identity==2"lvshi
					let newform = {
						"fromUserId": this.userMsg.id,
						"identity": this.userMsg.identity == 2 ? "lvshi" : "user",
						"destinationId": this.userMsg.identity == 2 ? this.newitem.userId : this.newitem.lawId,
						"destination": this.userMsg.identity == 2 ? "user" : "lvshi",
						"content": this.content,
						"type": "1",
						"chatRoomId": this.newitem.id,
					}
					this.socketTask.send({
						data: JSON.stringify(newform),
						async success() {
							that.dataList.push({
								fromUserIdHandlUrl: that.userMsg.handlUrl,
								...newform
							})
							// fromUserIdHandlUrl
							console.log("消息发送成功");
							uni.showToast({
								title: '消息发送成功',
								icon: 'none'
							})
							that.content = ''
							setTimeout(() => {
								that.scrollToBottom()
							}, 100)

						},
					});
				} else {
					uni.showToast({
						title: '连接失败,请稍后再试',
						icon: 'none'
					})
				}
			},
			connectSocketInit() {
				let that = this
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				let userName = this.userMsg.identity == 2 ? "lvshi" : "user"
				this.socketTask = uni.connectSocket({
					// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
					url: config.wsUrl + "/websocket/" + userName + "/" + this.userMsg.id,
					success(data) {
						that.scrollToBottom()
						console.log("websocket连接成功");
					},
				});

				// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");

					this.is_open_socket = true;
					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask.onMessage((res) => {
						console.log(that.imgUrl, 'imgUrl')
						if (res.data != '连接成功') {
							that.dataList.push({
								fromUserIdHandlUrl: that.imgUrl,
								...JSON.parse(res.data)
							})
						}

						setTimeout(() => {
							that.scrollToBottom()
						}, 500)

						console.log("收到服务器内容：" + res.data);
					});
				})
				// 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose(() => {
					console.log("已经被关闭了")
				})
			},
			// 关闭websocket【离开这个页面的时候执行关闭】
			closeSocket() {
				this.socketTask.close({
					success(res) {
						this.is_open_socket = false;
						console.log("关闭成功", res)
					},
					fail(err) {
						console.log("关闭失败", err)
					}
				})
			},
			clickRequest() {
				if (this.is_open_socket) {
					// websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
					this.socketTask.send({
						data: "请求一次发送一次message",
						async success() {
							console.log("消息发送成功");
						},
					});
				}
			},
			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
			InputBlur(e) {
				this.InputBottom = 0
			},
			scrollToBottom() {
				let that = this;
				let query = uni.createSelectorQuery();
				query.selectAll('.cu-item').boundingClientRect();
				query.select('#scrollview').boundingClientRect();
				query.exec((res) => {
					that.style.mitemHeight = 0;
					res[0].forEach((rect) => that.style.mitemHeight = that.style.mitemHeight + rect.height + 40) //获取所
					setTimeout(() => {
						if (that.style.mitemHeight > (that.style.contentViewHeight - 100)) { //判断子元素高度是否大于显示高度

							that.scrollTop = that.style.mitemHeight - that.style.contentViewHeight
							//用子元素的高度减去显示的高度就获益获得序言滚动的高度
							console.log(that.scrollTop)
						}
					}, 500)
				})
			},
			async loadMore() {
				this.isSHow = true
				console.log('加载更多', this.scrollY)
				uni.showLoading({
					title: '加载中...',
					icon: 'none'
				})
				let page = this.page
				let per_page = this.per_page
				let dataList = this.dataList
				page++;
				let dataListNextPage = await this.http.findMessageByPage({
					page,
					limit: per_page,
					chatRoomId: this.newitem.id
				});
				dataListNextPage.forEach(item => {
					item.createTime = this.timestampToTime(item.createTime)
				})
				uni.hideLoading()
				console.log(dataListNextPage, 'dataListNextPage')
				this.isSHow = false
				dataListNextPage.forEach(item => {
					this.dataList.unshift(item)
				})
				console.log(this.scrollTop)


				// 	this.scrollY = true
				if (dataListNextPage.length) {
					this.page = page;
				};
				if (!dataListNextPage.length) {
					this.print('没有更多了')
					return
				} else {
					this.scrollTop = this.scrollTop + 10
				}

			},
			async getMore() {
				this.page = 1
				let newObj = {
					page: this.page,
					limit: this.per_page,
					chatRoomId: this.newitem.id
				}
				let dataList = await this.http.findMessageByPage(newObj);
				dataList.forEach(item => {
					item.createTime = this.timestampToTime(item.createTime)
				})
				this.dataList = dataList
				console.log(this.dataList, 'this.dataList')
			},

		}
	}
</script>

<style>
	page {
		padding-bottom: 100upx;
		background-color: #f1f1f1 !important;
	}
</style>
